<template>
  <el-dialog :title="formData.id ? '编辑员工' : '添加员工'" :visible="showDialog" @close="closeFn">
    <el-form ref="form" label-width="100px" :model="formData" :rules="rules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="formData.username" placeholder="请输入用户名" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="formData.email" placeholder="请输入邮箱" />
      </el-form-item>
      <el-form-item v-if="isShow==false" label="密码" prop="password">
        <el-input v-model="formData.password" placeholder="请输入密码" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-row type="flex" justify="center">
        <el-button size="small" type="primary" @click="submit">确定</el-button>
        <el-button size="small" @click="closeFn">取消</el-button>
      </el-row>
    </template>
  </el-dialog>
</template>

<script>
import { addEmployee, getPersonalDetail, editEmployee } from '@/api/employees'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    isShow: {
      type: Boolean,
      default: true // 判断是否为编辑弹窗
    }
  },
  data() {
    return {
      formData: {
        username: '',
        email: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '用户名不能为空！', trigger: 'blur' },
          { min: 2, message: '长度至少 2 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空！', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        password: [
          { required: true, message: '密码不能为空！', trigger: 'blur' },
          { min: 6, message: '长度至少 6 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 添加员工提交按钮
    async submit() {
      // 表单校验
      await this.$refs.form.validate()
      // 发送请求时做判断 是否有id 有为编辑
      if (this.formData.id) {
        // 编辑
        await editEmployee(this.formData)
      } else {
        // 新增
        await addEmployee(this.formData)
      }
      // 更新列表
      this.$emit('updateEvent')
      this.closeFn()
    },

    // 关闭弹窗
    closeFn() {
      this.$emit('update:showDialog', false)
      // 清空数据
      this.formData = {
        username: '',
        email: '',
        password: ''
      }
      // 清空校验规则
      this.$refs.form.resetFields()
    },

    // 获取员工详情--编辑
    async getPersonalInfo(id) {
      const res = await getPersonalDetail(id)
      // console.log(93, res)
      this.formData = res.data
    }
  }
}
</script>

<style>

</style>
